<template>
    <el-container>
        <el-dialog width="80%" @close="$router.push({ name: 'LayerComponent' })" title="数据添加" :visible.sync="dialogFormVisible_addData" :append-to-body="true">
            <el-form size="mini" :model="add_form" ref="addDataForm" inline="true">
                <el-row>
                    <el-col :span="11">
                        <el-form-item size="mini" label="名称" :label-width="formLabelWidth" prop="name">
                            <el-input size="mini" v-model="add_form.name" autocomplete="off" style="width: 150px"></el-input>
                        </el-form-item>

                        <el-form-item size="mini" label="数据类型" :label-width="formLabelWidth" prop="name">
                            <el-select size="mini" v-model="add_form.datatype" style="width: 150px;" placeholder="请选择" @change="dropDown_dataType_selected($event)">
                                <el-option v-for="item in data.dataType" :key="item" :label="item" :value="item"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <!--      <el-form-item size="mini" label="任务类别" :label-width="formLabelWidth" prop="name">
                            <el-select size="mini" style="width: 150px;" v-model="taskCategories" filterable allow-create default-first-option placeholder="请选择类别">
                                <el-option v-for="item in taskCategoriesArr" :key="item" :label="item" :value="item"> </el-option>
                            </el-select>
                        </el-form-item>-->

                        <el-form-item size="mini" v-if="pathControl" label="路径" :label-width="formLabelWidth" prop="name">
                            <el-input size="mini" v-model="dataPath" autocomplete="off" style="width: 150px" readonly="true" @input="orderNoChange($event)"></el-input>
                            <el-button size="mini" type="primary" @click="importHandler">导入</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div id="prop_data">
                    <el-form-item size="mini" v-for="(domain, index) in add_form.domains" :label-width="formLabelWidth" :label="domain.key">
                        <el-input oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 150px" v-model="domain.value" @input="orderNoChange"></el-input>
                    </el-form-item>
                    <el-form-item size="mini" v-for="(domain, index) in add_form.domains_color" :label-width="formLabelWidth" :label="domain.key">
                        <el-color-picker v-model="domain.value" show-alpha></el-color-picker>
                    </el-form-item>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible_addData = false">取 消</el-button>
                <el-button type="primary" @click="addSave">确定</el-button>
            </div>
        </el-dialog>
    </el-container>
</template>

<script>
import LayerManager from "@/plugins/mev/layer/LayerManager";
import Environment from "@/plugins/utils/environment";
import loadJson from "@/plugins/utils/loadJson";

export default {
    name: "ToolbarAddDataComponent",
    data() {
        return {
            taskCategories: "",
            add_form: {},
            layerTreeData: [],
            dialogFormVisible_addData: false,
            formLabelWidth: "110px",
            taskCategoriesArr: [],
            data: {},
            pathControl: false,
            dataPath: ""
        };
    },
    beforeDestroy() {},
    created() {
        let that = this;
        this.dialogFormVisible_addData = true;

        let data = LayerManager.getInstance().getLayerData();
        that.layerTreeData = data;

        data.forEach(function(g) {
            that.taskCategoriesArr.push(g.name);
        });
        let path = Environment.getDataBasePath() + "layerTemplate.json";
        loadJson(path, function(data) {
            that.data = data;
        });
    },
    methods: {
        orderNoChange(e) {
            this.$forceUpdate();
        },
        initPropByDataType: function(data) {
            let that = this;
            let dataContent = that.data.dataContent[data];

            that.add_form.domains = [];
            that.add_form.domains_color = [];
            dataContent.forEach(function(item) {
                let obj = {};
                if (item.type === "color") {
                    obj.key = that.dictionaryTranslation(item.key);
                    obj.value = item.value;
                    that.add_form.domains_color.push(obj);
                } else if (item.type === "text") {
                    obj.key = that.dictionaryTranslation(item.key);
                    obj.value = item.value;
                    that.add_form.domains.push(obj);
                }
            });
        },
        //数据类型拉框选择触发
        dropDown_dataType_selected: function(data) {
            let that = this;
            that.pathControl = false;
            that.dataPath = "";
            that.pathControl = true;
            switch (data) {
                case LayerManager.GEOJSON:
                    that.add_form.domains = [];
                    that.taskCategories = "矢量数据";
                    break;
                case LayerManager.IMGPAK:
                    that.taskCategories = "影像数据";
                    break;
                case LayerManager.B3DM:
                    that.taskCategories = "模型数据";
                    that.initPropByDataType(data);
                    break;
                case LayerManager.GLTF:
                    that.taskCategories = "模型数据";
                    that.initPropByDataType(data);
                    break;
                case LayerManager.KML:
                    that.taskCategories = "矢量数据";
                    break;
            }
        },
        //geojson数据选择点线面触发
        dropDown_geojson_selected: function(data) {
            let that = this;
            that.initPropByDataType(LayerManager.GEOJSON + "_" + data);
            that.pathControl = true;
        },
        //点击导入按钮触发
        importHandler: function() {
            let that = this;
            //如果当前选择的数据类型为geojson，则要先选择geojson具体类型，否则return
            let flag = true;

            //判断当前的数据类型除bd3m数据选择数据文件夹外(flag为false), 其余都选择数据文件(flag为true)
            if (that.add_form.datatype === LayerManager.B3DM) {
                flag = false;
            }
            JavaContext.loadFileBrowser(flag, LayerManager.RootPath, true, "JsContext.onMarkGeoJsonImport");
            JsContext.onMarkGeoJsonImport = function(path) {
                that.dataPath = path;
                //执行导入方法获得路径，再对不同的路径进行处理，此操作中还要读取附加的参数文件对表单进行赋值，如果没有则不用
                // switch (that.add_form.datatype) {
                //     case LayerManager.GEOJSON:
                //         JavaContext.getTypeByGeoJson(path);
                //         that.initPropByDataType(LayerManager.GEOJSON + "_" + JavaContext.getTypeByGeoJson(path));
                //         break;
                // }
                let parameterPath = that.dealParameterPath(path);

                let obj = JSON.parse(JavaContext.ReadTxtFile(parameterPath));

                that.add_form.domains.forEach(function(item) {
                    if (obj[that.findKey(that.data.dictionary, item.key)]) {
                        item.value = obj[that.findKey(that.data.dictionary, item.key)];
                    }
                });

                that.add_form.domains_color.forEach(function(item) {
                    if (obj[that.findKey(that.data.dictionary, item.key)]) {
                        item.value = obj[that.findKey(that.data.dictionary, item.key)];
                    }
                });
            };
        },
        //添加完成后点击确定按钮触发
        addSave: function() {
            JavaContext.consoleLook("觉得撒可怜见的立刻撒旦0");
            let that = this;
            /* //将表单内容封装对象加入到layerTreeData并更新_jsonData
            LayerManager.getInstance().updateJsonData(that.layerTreeData);*/
            let resultObj = {};
            resultObj.datatype = that.add_form.datatype;
            resultObj.id = that.guid();
            resultObj.name = that.add_form.name;
            resultObj.path = that.dataPath;
            resultObj.visible = false;
            resultObj.properties = {};
            resultObj.properties.lineColor = "";
            resultObj.properties.width = "";
            resultObj.properties.fillColor = "";


            JavaContext.consoleLook(JSON.stringify(that.add_form.domains));

            JavaContext.consoleLook("觉得撒可怜见的立刻撒旦1");
            switch (that.add_form.datatype) {
                case LayerManager.IMGPAK:
                    resultObj.path = LayerManager.imgPrefix + resultObj.path;
                    break;
                case LayerManager.B3DM:
                    resultObj.path = resultObj.path + "/tileset.json";
                    that.add_form.domains.forEach(function(g) {
                        resultObj.properties[that.findKey(that.data.dictionary, g.key)] = parseFloat(g.value);
                    });

                    JavaContext.consoleLook("觉得撒可怜见的立刻撒旦01");
                    that.add_form.domains_color.forEach(function(g) {
                        if (resultObj.properties[that.findKey(that.data.dictionary, g.key)]) {
                            resultObj.properties[that.findKey(that.data.dictionary, g.key)] = g.value;
                        }
                    });
                    break;

                case LayerManager.KML:
                    break;
                default:

                    that.add_form.domains.forEach(function(g) {
                        resultObj.properties[that.findKey(that.data.dictionary, g.key)] = parseFloat(g.value);
                    });

                    // JavaContext.consoleLook("觉得撒可怜见的立刻撒旦01");
                    // that.add_form.domains_color.forEach(function(g) {
                    //     if (resultObj.properties[that.findKey(that.data.dictionary, g.key)]) {
                    //         resultObj.properties[that.findKey(that.data.dictionary, g.key)] = g.value;
                    //     }
                    // });
                    break;
            }
            JavaContext.consoleLook("觉得撒可怜见的立刻撒旦2");
            if (JSON.stringify(resultObj.properties) === JSON.stringify({})) {
                delete resultObj.properties;
            }
            let data = that.layerTreeData;
            JavaContext.consoleLook(that.taskCategories);
            JavaContext.consoleLook("觉得撒可怜见的立刻撒旦3");


            data.forEach(function(g) {
                if (g.name === that.taskCategories) {
                    // alert(string(resultObj));
                    resultObj.cesiumTreeData = LayerManager.getInstance().getCesiumTreeData(resultObj);
                    g.children.push(resultObj);
                }
            });
            JavaContext.consoleLook("觉得撒可怜见的立刻撒旦4");
            LayerManager.getInstance().updateJsonData(data);
            that.$message({
                showClose: true,
                message: "添加成功",
                type: "success"
            });
            JavaContext.consoleLook("觉得撒可怜见的立刻撒旦5");
            that.dialogFormVisible_addData = false;
        },
        dictionaryTranslation: function(name) {
            let that = this;
            return that.data.dictionary[name];
        },

        findKey: function(obj, value, compare = (a, b) => a === b) {
            return Object.keys(obj).find(k => compare(obj[k], value));
        },
        guid: function() {
            return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
                let r = (Math.random() * 16) | 0,
                    v = c === "x" ? r : (r & 0x3) | 0x8;
                return v.toString(16);
            });
        },
        dealParameterPath(path) {
            let that = this;
            if (that.add_form.datatype === LayerManager.B3DM) {
                return path + "/" + "parameter.json";
            } else {
                let str = path;
                let index = str.lastIndexOf("\/");
                str = str.substring(index + 1, str.length);
                let folder = path.replace(str, "");
                let w = str;
                let a = w.indexOf(".");
                let l = w.substring(0, a);
                return folder + l + "." + "parameter.json";
            }
        }
    }
};
</script>

<style scoped></style>
